package com.mylearn.myblog.service.impl;

import com.mylearn.myblog.dao.TypeRepository;
import com.mylearn.myblog.entity.Type;
import com.mylearn.myblog.service.TypeService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

	@Autowired
	private TypeRepository typeRepository;

	@Transactional
	@Override
	public Type saveType(Type type) {
		return typeRepository.save(type);
	}

	@Transactional
	@Override
	public Type getType(Long id) {
		return typeRepository.getOne(id);
	}

	@Override
	public Type getTypeByName(String name) {
		return typeRepository.findByName(name);
	}

	@Transactional
	@Override
	public Page<Type> listType(Pageable pageable) {
		return typeRepository.findAll(pageable);
	}

	@Transactional
	@Override
	public Type updateType(Long id, Type type) {
		Type t = typeRepository.getOne(id);
		if(t == null){
			try {
				throw new NotFoundException("Id 不存在");
			} catch (NotFoundException e) {
				e.printStackTrace();
			}
		}
		BeanUtils.copyProperties(type,t);
		t.setId(id);
		return typeRepository.saveAndFlush(t);

	}

	@Transactional
	@Override
	public void deleteType(Long id) {
		typeRepository.deleteById(id);
	}

	@Override
	public List<Type> listAll() {
		return typeRepository.findAll();
	}
}
